﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Agro.Models;
using SN.Data;
using Agro.Library;

namespace Agro.Services
{

    public class UserService : BaseService, IUserService
    {

        public bool SaveUser(T_User user, CurrentUser currUser, out string msg)
        {
            msg = string.Empty;

            if (!currUser.UserInfo.IsAdmin() && currUser.UserInfo.User_OrganizationID == user.User_OrganizationID)
            {
                msg = "不能添加或编辑同级用户！";
                return false;
            }
            if (user.User_ID > 0)
            {
                user.Attach();
            }
            else
            {
                if (DB.Exists<T_User>(T_User._.User_Code == user.User_Code))
                {
                    msg = "用户编号已存在";
                    return false;
                }
                user.Detach();
            }
            
            //暂不加密
            //user.User_Password = SN.Core.Helper.Cryptography.MD5Encrypt(user.User_Password);
            DB.Save(user);
            return true;
        }

        public string SaveUserMenus(int userId, string menuIds) {
            string Msg = string.Empty;
            using (DbTrans trans = DB.BeginTrans()) {
                try {
                    trans.Delete<T_UserMenu>(T_UserMenu._.UserID == userId);
                    string[] menuIdArray = menuIds.Split(',');
                    DbBatch batch = trans.BeginBatch(menuIdArray.Length);
                    foreach (var menuId in menuIdArray) {
                        if (string.IsNullOrEmpty(menuId)) continue;
                        T_UserMenu userMenu = new T_UserMenu();
                        userMenu.UserID = userId;
                        userMenu.MenuID = int.Parse(menuId);
                        userMenu.Detach();
                        batch.Save(userMenu);
                    }
                    batch.Process();
                    trans.Commit();
                }
                catch (Exception ex) {
                    trans.Rollback();
                    Msg = ex.Message;
                }
            }
            return Msg;
        }


        public bool DeleteUsers(string ids, out string msg)
        {
            msg = string.Empty;
            int iCount = 0;
            string[] arrayUser = ids.Split(',');
            for (int i = 0; i < arrayUser.Length; i++)
            {
                iCount = DB.Count<T_User_Role>(T_User_Role._.UR_UserID == arrayUser[i]);
                if (iCount > 0)
                {
                    msg = "用户已在用户-角色表中使用，不允许删除!";
                    return false;
                }
                //判断功能表中是否已经使用
                iCount = DB.Count<T_User_Permission>(T_User_Permission._.UP_UserID == arrayUser[i]);
                if (iCount > 0)
                {
                    msg = "用户已在功能权限表中使用，不允许删除!";
                    return false;
                }
                //判断是否已经填报过数据
                iCount = DB.Count<T_SubmitInfo>(T_SubmitInfo._.SubmitInfo_CreatorID == arrayUser[i]);
                if (iCount > 0)
                {
                    msg = "用户已填报数据，不允许删除!";
                    return false;
                }
            }
            DB.Delete<T_User>(T_User._.User_ID.In(ids.Split(',')));
            return true;
        }


        public System.Data.DataTable GetUserList(SN.Core.QueryBase query, WhereClip wclip)
        {
            Field[] fields = { 
                               T_User._.All,
                               T_Organization._.Organization_Name,T_Organization._.Organization_ID
                             };
            var section = DB.From<T_User>()
                .InnerJoin<T_Organization>(T_Organization._.Organization_ID == T_User._.User_OrganizationID)
                .Where(wclip);
            var dt = section.ToTablePage(query, fields);
            return dt;
        }


        public string ChangePassword(string UserId, string Password)
        {
            if (string.IsNullOrWhiteSpace(Password)) return "新密码不能为空!";
            int iReturn = DB.Update<T_User>(T_User._.User_Password,Password, T_User._.User_ID == UserId);//此处返回值为2，通常情况下是1，但因为t_user表有update触发器，故返回值为2
            if (iReturn >= 1)
            {
                return "";
            }
            else
            {
                return "密码修改失败!";
            }
        }

        public void SaveUserActions(int userId, int menuId, string actionIds) {
            using (DbTrans trans = DB.BeginTrans()) {
                try {
                    IList<T_Action> actionList = trans.From<T_Action>().Where(T_Action._.MenuID == menuId).ToList();
                    if (actionList.Count > 0) {
                        trans.Delete<T_UserAction>(T_UserAction._.UserID == userId && T_UserAction._.ActionID.In(actionList.Select(m => m.ActionID).ToArray()));
                    }
                    string[] actionIdArray = actionIds.Split(',');
                    DbBatch batch = trans.BeginBatch(actionIdArray.Length);
                    foreach (var actionId in actionIdArray) {
                        if (string.IsNullOrEmpty(actionId)) continue;
                        T_UserAction userAction = new T_UserAction();
                        userAction.ActionID = Convert.ToInt32(actionId);
                        userAction.UserID = userId;
                        userAction.Detach();
                        batch.Save(userAction);
                    }
                    batch.Process();
                    trans.Commit();
                }
                catch (Exception) {
                    trans.Rollback();
                    throw;
                }
            }
        }
     
    }
}
